<template>
    <div class="box">
        <div v-if="billData.id" class="top">
            <div class="back" @click="$router.back()">
                <svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M25 5L10 20L25 35" stroke="white" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
            <div class="font_title">
                <svgIcon :iconName="billData.icon || 'icon-jiangjin'" font-size="80px"></svgIcon>
                <p>{{ billData.category || '未分类' }}</p>
            </div>
        </div>
        <div v-if="billData.id" class="cont">
            <div class="item">
                类型 <span>{{ billData.type === 'expense' ? '支出' : '收入' }}</span>
            </div>
            <div class="item">
                金额 <span>{{ billData.amount?.toFixed(2) || '0.00' }}</span>
            </div>
            <div class="item">
                备注 <span>{{ billData.category || '未分类' }}</span>
            </div>
            <div class="item">
                时间 <span>{{ formatDateTime(billData.time) }}</span>
            </div>
        </div>
        <div v-if="billData.id" class="bottom">
            <div class="updata" @click="handleUpdate">
                修改
            </div>
            <div class="del" @click="handleDelete">
                删除
            </div>
        </div>

        <!-- 确认删除弹窗 -->
        <div v-if="showConfirmDialog" class="confirm-dialog">
            <div class="dialog-content">
                <h3>确认删除</h3>
                <p>确定要删除这条账单记录吗？</p>
                <div class="dialog-buttons">
                    <button @click="confirmDelete" class="confirm-btn">确认</button>
                    <button @click="showConfirmDialog = false" class="cancel-btn">取消</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import request from '../utils/request';

const router = useRouter();
const route = useRoute();
const billData = ref({
    id: '',
    _id:'',
    type: '',
    amount: 0,
    category: '',
    icon: '',
    time: '',
    order: 0
});
const showConfirmDialog = ref(false);

onMounted(() => {
    // 从路由query参数中获取账单数据
    const query = route.query;
    if (query.id) {
        billData.value = {
            id: query.id,
            _id:query._id,
            type: query.type || '',
            amount: parseFloat(query.amount) || 0,
            category: query.category || '',
            icon: query.icon || 'icon-jiangjin',
            time: query.time || '',
            order: parseInt(query.order) || 0
        };
        console.log('时间数据:', query.time);
        console.log('获取到的账单数据:', billData.value);
    } else {
        console.log('未获取到账单数据');
        router.back();
    }
});
console.log(billData.value);
// 格式化日期时间
const formatDateTime = (dateStr) => {
    try {
        if (!dateStr) return '无效日期';
        
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) return '无效日期';
        
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        
        return `${year}-${month}-${day} ${hours}:${minutes}`;
    } catch (err) {
        console.error('日期格式化错误:', err);
        return '无效日期';
    }
};

// 处理更新
const handleUpdate = () => {
    router.push({
        name: 'cart',
        query: {
            id: billData.value.id,
            _id: billData.value._id,
            type: billData.value.type,
            amount: billData.value.amount,
            category: billData.value.category,
            icon: billData.value.icon,
            time: billData.value.time,
            order: billData.value.order,
            isEdit: true
        }
    });
};

// 处理删除
const handleDelete = () => {
    showConfirmDialog.value = true;
};

// 确认删除
const confirmDelete = async () => {
    try {
        console.log('准备删除的账单数据:', billData.value);
        // 先获取当前类别的所有数据
        const response = await request.get('/api/category/categories', null, {
            headers: {
                'Content-Type': 'application/json'
            }
        });
        console.log('获取到的所有类别数据:', response.data);
        
        const category = response.data.find(item => item.id === billData.value.id);
        console.log('找到的类别数据:', category);
        
        if (!category) {
            throw new Error('未找到对应的类别');
        }

        // 确保data是数组
        if (!Array.isArray(category.data)) {
            throw new Error('类别数据格式错误');
        }

        // 过滤掉要删除的记录
        const updatedData = category.data.filter(item => item._id !== billData.value._id);
        console.log('原始数据:', category.data);
        console.log('更新后的数据:', updatedData);
        
        // 构建更新数据
        const updateData = {
            name: category.name,
            type: category.type,
            icon: category.icon,
            order: category.order,
            data: updatedData
        };

        console.log('发送到服务器的更新数据:', updateData);
        console.log('请求URL:', `/api/category/categories/${category._id}`);
        
        // 使用PUT请求更新类别数据
        const updateResponse = await request.put(`/api/category/categories/${category._id}`, updateData, {
            headers: {
                'Content-Type': 'application/json'
            }
        });
        console.log('服务器响应:', updateResponse.data);
        
        showConfirmDialog.value = false;
        // 删除成功后返回上一页
        router.back();
    } catch (error) {
        console.error('删除失败:', error);
        if (error.response) {
            console.error('服务器响应数据:', error.response.data);
            console.error('服务器响应状态:', error.response.status);
        }
        alert(error.message || '删除失败，请稍后重试');
    }
};
</script>

<style lang='less' scoped>
.box {
    width: 100%;
    min-height: 100vh;
    overflow: hidden;
    .top {
        width: 100%;
        height: 170px;
        background-color: #fb8fae;
        color: #fff;
        position: fixed;
        top: 0;
        left: 0;
        z-index: 100;
        display: flex;
        align-items: center;
            .back {
                width: 120px;
                height: 100%;
                margin-left: 30px;
                line-height: 50px;
                // text-align: center;
                svg {
                    margin-top: 40px;
                    width: 40px;
                    height: 40px;
                }
            }
            .font_title {
                margin-left: 180px;
                text-align: center;
                font-size: 28px;
            }
    }
    .cont {
        width: 100%;
        margin-top: 170px;
        background-color: fbfbf1;
        div {
            margin-left: 30px;
            width: 720px;
            border-bottom: 2px solid gray;
            height: 100px;
            line-height: 100px;
            color: gray;
            font-size: 28px;
            span {
                margin-left: 20px;
                color: #000;

            }
        }
    }
    .bottom {
        width: 100%;
        height: 100px;
        border-top: 2px solid gray;
        text-align: center;
        font-size: 32px;
        display: flex;
        position: fixed;
        bottom: 0;
        .updata {
            width: 373px;
            height: 100px;
            line-height: 100px;
            border-right: 2px solid gray;
        }
        .del {
            width: 375px;
            height: 100px;
            line-height: 100px;
        }
    }
}

.confirm-dialog {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;

    .dialog-content {
        background: white;
        padding: 30px;
        border-radius: 10px;
        width: 80%;
        max-width: 500px;

        h3 {
            font-size: 32px;
            margin-bottom: 20px;
            text-align: center;
        }

        p {
            font-size: 28px;
            color: #666;
            text-align: center;
            margin-bottom: 30px;
        }

        .dialog-buttons {
            display: flex;
            justify-content: space-around;

            button {
                padding: 15px 40px;
                border: none;
                border-radius: 5px;
                font-size: 28px;
                cursor: pointer;

                &.confirm-btn {
                    background: #ff9bb7;
                    color: white;
                }

                &.cancel-btn {
                    background: #f5f5f5;
                    color: #666;
                }
            }
        }
    }
}
</style>